<?php
/**
 * Created on 22.12.2005
 * 
 * <a href="#" onclick="<ajax:function action="seb::form2" update="anzeige" error="error">">link</a>
 * 
 * update or update, error, load or error, load
 * 
 * update => id of element to update
 * load, error => name of callback functions
 * 
 * if 'update' is not used, the form is not updated (validationErrorStyle)
 * 
 * var -> like c:url
 * 
 * EL not allowed:
 * 
 * 
 * EL allowed:
 * value
 * action
 * module
 * var
 */

// TODO add target attribute, if validate name is required
class ajax_functionHandler
{
    
    var $name = null;
    var $attrs;
    var $line;

    function startElement (& $sender, $attrs, $line)
    {
        $this->attrs = $attrs;
        if (empty($attrs['value']) && empty($attrs['action']))
        {
            die ("Attribute value or action is missing in ajax:function tag in line $line!\n");
        }
        $attrs['tag'] = 'url';
        if (empty($attrs['var']))
            unset($this->var);
        else
            $this->var = $attrs['var'];
        $sender->pushParent($attrs);
        if ($attrs['value'])
        {
            $sender->appendCode('$'."__url = new phpinchains_tagsupport_URL(\$env, ".$attrs['value'].");\n");
        }
        else
        {
            $sender->appendCode('$'."__url = new phpinchains_tagsupport_URL(\$env);\n");
        }
        if ($attrs['action'])
        {
            $sender->appendCode('$'."__url->setAction(".$attrs['action'].");\n");
        }
        if ($attrs['module'])
        {
            $sender->appendCode('$'."__url->setModule(".$attrs['module'].");\n");
        }
        $sender->appendCode('$__'."url->addParam('jsresponse' , 'true');\n");        
       	$sender->appendCode("\$run = &phpinchains_RuntimeConfig::getInstance();\n");
       	$sender->appendCode("if (\$run->get('sec_code_enabled')) {\n");
       	$sender->appendCode('    $'."__url->addParam('__ss', \$env->getSession('phpinchains_sec_code'));\n");
       	$sender->appendCode("}\n");
       	$sender->appendCode("if (\$run->get('additional_parameters')) {\n");
       	$sender->appendCode('    $'."__url->addParams(\$run->get('additional_parameters'));\n");
       	$sender->appendCode("}\n");
    }

    function endElement (& $sender)
    {
        $attrs = $this->attrs;
        $run = &phpinchains_RuntimeConfig::getInstance();
        $actionParam   = $run->get("actionParam");
        $actionParamId = $run->get("actionParamId");
        $moduleParam   = $run->get("moduleParam");
        $moduleParamId = $run->get("moduleParamId");
        if (!$attrs['value'] && !$attrs['action'])
        {
            die ("Attribute value or action is missing in ajax:function tag in line $line!\n");
        }
        $parent = $sender->topParent();
        $sender->popParent();
        $fname = 'phpinchains.func.ajaxfunction'.md5(time()+rand());
        // old with php code in JSCode
        if ($attrs['update'])
        {
            $js = str_replace("'", "'", '        '.$fname.' = function (type, data, evt) {'.      
                'var callback;'.
                'if (type == \'load\') {'.
                 'dojo.byId(');
            $js .= "\''.".$attrs['update'].".'\'";
            $js .= ').innerHTML = data;';
            if ($attrs['load'])
            {
                $js .= '            callback = ';
                $js .= "'.".$attrs['load'].".'";
                $js .= '; callback(type, data, evt);';
            }
            $js .= '} else {';
            if ($attrs['error'])
            {
                $js .= '            callback = ';
                $js .= ("'.".$attrs['error'].".'");
                $js .= '; callback(type, data, evt);';
            }
            $js .= '}'.
                '}';
            $sender->appendJSCode($js);
            $attrs['handle'] = $fname;
        }
        elseif ($attrs['jsresponse'] == "'true'")
        {
/*            $js = '        '.$fname.' = function (type, data, evt) {'      
//        .'var obj = eval(\\\\\\\'(\\\\\\\'+evt.responseText+\\\\\\\')\\\\\\\');'
        .'var callback;'
        .'type = \\\'load\\\';'
        .'if (type == \\\'load\\\') {'
//            .'var resfunobj = eval(\\\'({ \\\\\\\'fun\\\\\\\': \\\'+obj.result + \\\\\\\'})\\\\\\\')'
            .'var resfunobj = eval(\\\'({ \\\\\\\'fun\\\\\\\': \\\'+evt.responseText + \\\'})\\\');'
            .'resfunobj.fun();'
            .'dojo.hostenv.makeWidgets();phpinchains.onAfterUpdate();';
            if ($attrs['load'])
                $js .= '            callback = '.str_replace("'", "", $attrs['load']).'; callback(type, data, evt);';
            $js .= '        } else { '
            .'dojo.hostenv.makeWidgets();phpinchains.onAfterUpdate();';
            if ($attrs['error'])
                $js .= '            callback = '.str_replace("'", "", $attrs['error']).'; callback(type, data, evt);';
            $js .= '        } }';*/
            $js = '        '.$fname.' = function (type, data, evt) {'      
        .'var callback;'
        .'type = \'load\';'
        .'if (type == \'load\') {'
            .'var resfunobj = eval(\'({ \\\'fun\\\': \'+evt.responseText + \'})\');'
            .'resfunobj.fun();'
            .'dojo.hostenv.makeWidgets();phpinchains.onAfterUpdate();';
            if ($attrs['load'])
                $js .= '            callback = '.str_replace("'", "", $attrs['load']).'; callback(type, data, evt);';
            $js .= '        } else { '
            .'dojo.hostenv.makeWidgets();phpinchains.onAfterUpdate();';
            if ($attrs['error'])
                $js .= '            callback = '.str_replace("'", "", $attrs['error']).'; callback(type, data, evt);';
            $js .= '        } };';
            if ($attrs['onhandle'])
                $attrs['handle'] = "'function (type, data, evt) {'.".$attrs['onhandle'].".';$fname(type, data, evt);}'";
            elseif ($attrs['handle'])
                $attrs['handle'] = "'function (type, data, evt) {'.".$attrs['handle'].".';$fname(type, data, evt);}'";
            else 
            {
            	$sender->appendJSCode($js);
            	$attrs['handle'] = $fname;
            }
        }
        $js = '$__js .= \'dojo.io.bind({\';';
        if ($attrs['load'] && !$attrs['update'])
            $js .= '$__js .= \' load: \'.'.$attrs['load'].'.",";';
        if ($attrs['error'] && !$attrs['update'])
            $js .= '$__js .= \' error: \'.'.$attrs['error'].'.",";';
        if ($attrs['handle'])
            $js .= '$__js .= \' handle: '.$attrs['handle'].',\';';
        $js .= '$__js .= \' url: \\\'\'.$__url->toString()."\'";'
            .'$__js .= \'});\';';
        $tag .= '$__js = "try{";'
            .$js
            .'$__js .= "}catch(e){};return false;";'."\n";
        $sender->appendCode($tag);
        if ($this->var)
            $sender->appendCode('$actionform->set('.$this->var.', $'."__js);\n");
        else
            $sender->appendCode('$out->write($'."__js);\n");
    }

}

?>